export default function throttle(fn, wait = 250) {
    let previous = 0;
    let timeout = null;
    let result;
    let storedContext;
    let storedArgs;

    const later = () => {
        previous = Date.now();
        timeout = null;
        result = fn.apply(storedContext, storedArgs);

        if (!timeout) {
            storedContext = null;
            storedArgs = [];
        }
    };

    return function (...args) {
        const now = Date.now();
        const remaining = wait - (now - previous);
        storedContext = this;
        storedArgs = args;

        if (remaining <= 0 || remaining > wait) {
            if (timeout) {
                clearTimeout(timeout);
                timeout = null;
            }

            previous = now;
            result = fn.apply(storedContext, storedArgs);

            if (!timeout) {
                storedContext = null;
                storedArgs = [];
            }
        } else if (!timeout) {
            timeout = setTimeout(later, remaining);
        }

        return result;
    };
}
